package com.leyou.gateway.filters;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FilterProperties filterProp;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.获取请求路径
        String path = request.getRequestURI();
        // 3.判断路径是否存在与白名单
        boolean isAllowed = isAllowedPath(path);
        // 是否执行run方法，如果是要放行的请求，应返回false， 如果是拦截的请求，应该返回true
        return !isAllowed;
    }

    private boolean isAllowedPath(String path) {
        // 所有的白名单
        List<String> allowPaths = filterProp.getAllowPaths();
        // 判断的是否是许可的路径
        for (String allowPath : allowPaths) {
            if(StringUtils.startsWith(path, allowPath)){
                // 在白名单，放行
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        // 0.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 1.获取cookie
            String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());

            // 2.解析token,取出用户
            Payload<UserInfo> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            } catch (Exception e) {
                throw new RuntimeException("登录已经失效！", e);
            }

            // 3.校验黑名单
            Boolean exists = redisTemplate.hasKey(payload.getId());
            if (exists != null && exists) {
                // token已经失效
                throw new RuntimeException("登录已经失效！");
            }

            // 4.获取用户的id，根据id查询权限
            UserInfo userInfo = payload.getUserInfo();
            String role = userInfo.getRole();
            // 5.获取请求路径request.GetRequestURI();.
            String path = request.getRequestURI();
            // TODO 6.判断用户权限
            log.info("用户{}， 角色{}， 正在访问【{}】资源！", userInfo.getUsername(), role, path);

        } catch (RuntimeException e) {
            // 校验登录状态失败，拦截
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
        }
        return null;
    }
}
